/*
 * Copyright 2023 devaper
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.github.devaper.pigeon.intercept

import io.github.devaper.pigeon.request.*
import java.util.*

class RequestInterceptorComposite(
    requestInterceptors: List<RequestInterceptor>
) : RequestInterceptor {

    private val requestInterceptors = LinkedList(requestInterceptors)

    override fun intercept(methodContext: io.github.devaper.pigeon.MethodContext, requestTemplate: RequestTemplate) {
        if (requestInterceptors.isNotEmpty()) {
            requestInterceptors.forEach { requestInterceptor ->
                requestInterceptor.intercept(methodContext, requestTemplate)
            }
        }
    }

    fun join(requestInterceptors: List<RequestInterceptor>): RequestInterceptorComposite {
        val composite = RequestInterceptorComposite(this.requestInterceptors)
        composite.requestInterceptors.addAll(requestInterceptors)
        return composite
    }

    companion object {

        fun merge(requestInterceptor0: RequestInterceptor, requestInterceptor1: RequestInterceptor): RequestInterceptorComposite {
            return if (requestInterceptor0 is RequestInterceptorComposite) {
                if (requestInterceptor1 is RequestInterceptorComposite) {
                    requestInterceptor0.join(requestInterceptor1.requestInterceptors)
                } else {
                    requestInterceptor0.join(listOf(requestInterceptor1))
                }
            } else {
                if (requestInterceptor1 is RequestInterceptorComposite) {
                    val requestInterceptors = mutableListOf(requestInterceptor0)
                    requestInterceptors.addAll(requestInterceptor1.requestInterceptors)
                    RequestInterceptorComposite(requestInterceptors)
                } else {
                    RequestInterceptorComposite(listOf(requestInterceptor0, requestInterceptor1))
                }
            }
        }

    }
}